package com.torfox.modules.logview;

import javax.jms.Connection;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;

public class Log4jJMSAppenderExample implements MessageListener
{

	public Log4jJMSAppenderExample() throws Exception {
		// create a logTopic topic consumer
		final ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
		final Connection conn = factory.createConnection();
		final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
		conn.start();
		final MessageConsumer consumer = sess.createConsumer(sess.createTopic("logTopic"));
		consumer.setMessageListener(this);
		// log a message
		final Logger log = Logger.getLogger(Log4jJMSAppenderExample.class);
		log.info("Test log");
		// clean up
		Thread.sleep(100000000);
		consumer.close();
		sess.close();
		conn.close();
		System.exit(1);
	}

	public static void main(final String[] args) throws Exception {
		new Log4jJMSAppenderExample();
	}

	@Override
    public void onMessage(final Message message) {
		try {
			// receive log event in your consumer
			final LoggingEvent event = (LoggingEvent)((ActiveMQObjectMessage)message).getObject();
			System.out.println("Received log [" + event.getLevel() + "]: "+ event.getMessage());
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
}
